const { buyNow, getCart, submitFormGoods, submitFormCart, creditInfo, submitForCredit, getCredit } = require('../../api/confirm-order')
// const { buyCourse } = require('../../api/course')
const { API_OK } = require('../../utils/setting')
const { add, sub, mul, div } = require('../../utils/util')
// const app =  getApp()

Page({
  data: {
    isCreditOrder: false, // 是否是积分订单，积分订单必须使用最大可用积分
    ratio: 1,
    showAddress: true,
    addressInfo: null,
    selectVisible: false,
    expressType: [0], // 0:物流, 1:自提
    expressPrice: 0,
    cart: [],
    totalNumber: 0,
    totalPrice: 0,
    credit: 0,
    totalCredit: 0,
    useCredit: false
  },
  pageData: {
    options: {},
    submit: false,
    selectChangeValue: 0,
    canClosePicker: false
  },
  onLoad: function (options) {
    // console.log(options)
    this.pageData.options = options
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    prevPage.pageData && (prevPage.pageData.refresh = true)
    this.setData({
      isCreditOrder: options.order_type === 'credit',
      showExpress: options.order_type !== 'course'
    })
  },
  /**
   * 更新选择的地址
   */
  async onShow() {
    // console.log(this.chooseAddressCallback)
    // await this.getCreditInfo()
    if (this.chooseAddressCallback) {
      this.setData({
        addressInfo: this.chooseAddressCallback()
      }, () => {
        this.getOrder()
      })
    } else {
      this.getOrder()
    }
  },
  /**
   * 切换物流选择器显示状态
   */
  changeVisibleStatus({ currentTarget }) {
    this.setData({ selectVisible: currentTarget.dataset.status })
  },
  pickStart() {
    this.pageData.canClosePicker = false
  },
  pickEnd() {
    this.pageData.canClosePicker = true
  },
  /**
   * 物流选择器的 change 事件
   */
  handleSelectChange(e) {
    // console.log(e)
    this.pageData.selectChangeValue = e.detail.value[0]
  },
  /**
   * 选择物流方式
   */
  chooseExpressType() {
    if (!this.pageData.canClosePicker) return
    this.setData({
      expressType: [this.pageData.selectChangeValue],
      selectVisible: false
    })
    this.pageData.canClosePicker = false
    this.calcTotal()
  },
  /**
   * 获取积分信息
   */
  // async getCreditInfo() {
  //   try {
  //     const res = await creditInfo()
  //     // console.log(res)
  //     if (res.code === API_OK) {
  //       this.setData({
  //         totalCredit: res.data.score * 1,
  //         ratio: res.data.ratio * 1
  //       })
  //     }
  //   } catch(err) {
  //     console.warn(err)
  //   }
  // },
  /**
   * 获取订单信息
   */
  async getOrder() {
    if (this.pageData.options.order_type === 'course') {
      this.setData({
        cart: [{...this.pageData.options, number: 1, stock: 1}],
        showAddress: false
      }, () => {
        this.calcTotal()
      })
    } else {
      this.getOrderInfo()
    }
  },
  /**
   * 跳转地址选择页面
   */
  chooseAddress() {
    wx.navigateTo({ url: '/pages/address/address?type=chooseAddress' })
  },
  /**
   * 计算总价和商品数量
   */
  calcTotal() {
    let price = 0, number = 0
    // let credit= 0
    this.data.cart.forEach(goods => {
      price = add(goods.price * goods.number, price)
      number = add(goods.number, number)
      // credit = add(goods.credit * goods.number, credit)
    })
    // console.log(price, number, credit)
    // if (this.data.isCreditOrder) {
    //   // 积分商品
    //   const diff = credit - this.data.totalCredit > 0 ? credit - this.data.totalCredit : 0
    //   credit = Math.min(credit, this.data.totalCredit)
    //   price = add(
    //     mul(
    //       diff,
    //       div(1, this.data.ratio)
    //     ),
    //     price
    //   )
    // } else if (!this.data.showExpress) {
    //   /** 课程订单只需要计算 credit，不需要任何处理 */
    // } else {
    //   // 其他商品
    //   credit = Math.min(credit, this.data.totalCredit, price * this.data.ratio)

    //   price = sub(
    //     price,
    //     mul(
    //       this.data.useCredit ? credit : 0,
    //       div(1, this.data.ratio)
    //     )
    //   )
    //   // 如果价格被减到负数，减少积分的使用量，调整价格到 0
    //   if (price < 0) {
    //     credit = sub(credit, mul(Math.abs(price), this.data.ratio))
    //     price = 0
    //   }
    // }
    this.setData({
      totalNumber: number,
      totalPrice: price,
      // credit,
      // useCredit: credit === 0 ? false : this.data.useCredit
    })
  },
  /**
   * 减少商品数量
   */
  decrease(e) {
    const { index } = e.currentTarget.dataset
    if (this.data.cart[index].number <= 1) {
      wx.showToast({ title: '数量不能再减少了', icon: 'none', duration: 1500, mask: false })
      return
    }
    this.data.cart[index].number -= 1
    this.setData({ cart: this.data.cart })
    this.calcTotal()
  },
  /**
   * 增加商品数量
   */
  increase(e) {
    const { index } = e.currentTarget.dataset
    if (this.data.cart[index].number >= this.data.cart[index].stock) {
      wx.showToast({ title: '数量不能再增加了', icon: 'none', duration: 1500, mask: false })
      return
    }
    this.data.cart[index].number += 1
    this.setData({ cart: this.data.cart })
    this.calcTotal()
  },
  /**
   * 获取订商品类单信息
   */
  getOrderInfo() {
    if (this.pageData.options.order_type === 'cart') {
      return this.getCart()
    } else if (this.pageData.options.order_type === 'buyNow') {
      return this.getGoods()
    }
    // else {
    //   return this.getCreditGoods()
    // }
  },
  /**
   * 是否使用积分
   */
  // toggleUseCredit() {
  //   if (this.data.isCreditOrder || !this.data.credit) return
  //   this.setData({ useCredit: !this.data.useCredit })
  //   this.calcTotal()
  // },
  /**
   * 查询积分商品
   */
  // async getCreditGoods() {
  //   try {
  //     wx.showLoading({ title: '拼命加载中', mask: true })
  //     const res = await getCredit({
  //       data: {
  //         goods_id: this.pageData.options.goods_id,
  //         goods_num: this.pageData.options.goods_num,
  //         goods_sku_id: this.pageData.options.goods_sku_id,
  //         address_id: this.data.addressInfo && this.data.addressInfo.address_id,
  //         is_self: this.data.expressType[0]
  //       },
  //       callback: wx.hideLoading
  //     })
  //     // console.log(res)
  //     if (res.code === API_OK) {
  //       this.setData({
  //         expressPrice: res.data.express_price,
  //         cart: res.data.goods_list.map(item => {
  //           return {
  //             id: item.goods_id,
  //             image: item.image && item.image.length && item.image[0].file_path,
  //             name: item.goods_name,
  //             price: item.goods_price,
  //             number: item.total_num * 1,
  //             specifications: item.goods_sku.goods_attr,
  //             stock: item.goods_sku.stock_num,
  //             credit: item.score_deduct * 1
  //           }
  //         })
  //       })
  //       this.calcTotal()
  //     }
  //   } catch(err) {
  //     console.warn(err)
  //   }
  // },
  /**
   * 商品信息
   */
  async getGoods() {
    try {
      wx.showLoading({ title: '拼命加载中', mask: true })
      const res = await buyNow({
        data: {
          goods_id: this.pageData.options.goods_id,
          goods_num: this.pageData.options.goods_num,
          goods_sku_id: this.pageData.options.goods_sku_id,
          address_id: this.data.addressInfo && this.data.addressInfo.address_id,
          is_self: this.data.expressType[0]
        },
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === API_OK) {
        this.setData({
          expressPrice: res.data.express_price,
          cart: res.data.goods_list.map(item => {
            return {
              id: item.goods_id,
              image: item.image && item.image.length && item.image[0].file_path,
              name: item.goods_name,
              price: item.goods_price,
              number: item.total_num * 1,
              specifications: item.goods_sku.goods_attr,
              stock: item.goods_sku.stock_num,
              credit: item.score_deduct * 1
            }
          })
        })
        this.calcTotal()
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 购物车信息
   */
  async getCart() {
    try {
      wx.showLoading({ title: '拼命加载中', mask: true })
      const res = await getCart({
        data: {
          cart_ids: this.pageData.options.cart_ids,
          address_id: this.data.addressInfo && this.data.addressInfo.address_id,
          is_self: this.data.expressType[0]
        },
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === API_OK) {
        this.setData({
          addressInfo: res.data.address,
          expressPrice: res.data.express_price,
          cart: res.data.goods_list.map(item => {
            return {
              id: item.goods_id,
              image: item.image && item.image.length && item.image[0].file_path,
              name: item.goods_name,
              price: item.goods_price,
              number: item.total_num * 1,
              specifications: item.goods_sku.goods_attr,
              stock: item.goods_sku.stock_num,
              credit: item.score_deduct * 1
            }
          })
        })
        this.calcTotal()
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 提交订单
   */
  submitOrder() {
    if (this.pageData.submit) return
    if (!this.data.addressInfo && this.data.showAddress) {
      wx.showToast({ title: '请选择收货地址', icon: 'none', duration: 1500, mask: false })
      return
    }
    // if (this.data.totalCredit < this.data.credit) {
    //   wx.showToast({ title: '积分不足', icon: 'none', duration: 1500 })
    //   return
    // }

    wx.showLoading({ title: '正在提交', mask: true })

    if (this.pageData.options.order_type === 'cart') {
      return this.submitCartOrder()
    } else if (this.pageData.options.order_type === 'buyNow') {
      return this.submitGoodsOrder()
    }
    // else if (this.pageData.options.order_type === 'credit') {
    //   return this.submitCreditOrder()
    // } else {
    //   return this.submitCourseOrder()
    // }
  },
  /**
   * 提交积分商品订单
   */
  // async submitCreditOrder() {
  //   try {
  //     const res = await submitForCredit({
  //       data: {
  //         goods_id: this.pageData.options.goods_id,
  //         goods_num: this.data.cart[0].number,
  //         goods_sku_id: this.pageData.options.goods_sku_id,
  //         address_id: this.data.addressInfo.address_id,
  //         is_self: this.data.expressType[0],
  //         remark: ''
  //       },
  //       callback: wx.hideLoading
  //     })
  //     // console.log(res)
  //     if (res.code === API_OK) {
  //       this.pageData.submit = false
  //       this.pay(res.data.payment)
  //     }
  //   } catch(err) {
  //     wx.hideLoading()
  //     console.warn(err)
  //     this.pageData.submit = false
  //   }
  // },
  /**
   * 提交购物车订单
   */
  async submitCartOrder() {
    try {
      const res = await submitFormCart({
        data: {
          cart_ids: this.pageData.options.cart_ids,
          is_self: this.data.expressType[0],
          remark: '',
          use_score: this.data.useCredit ? 1 : 0
        },
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === API_OK) {
        this.pageData.submit = false
        if (res.data.status) {
          wx.showToast({
            title: res.data.status === 1 ? '购买成功' : '购买失败',
            icon: 'success',
            duration: 1500,
            mask: false,
            success: () => {
              setTimeout(() => {
                if (res.data.status === 1) wx.navigateBack({ delta: 1 })
              }, 1500)
            }
          })
        } else {
          this.pay(res.data.payment)
        }
      }
    } catch(err) {
      console.warn(err)
      this.pageData.submit = false
    }
  },
  /**
   * 提交商品订单
   */
  async submitGoodsOrder() {
    try {
      const res = await submitFormGoods({
        data: {
          goods_id: this.pageData.options.goods_id,
          goods_num: this.data.cart[0].number,
          goods_sku_id: this.pageData.options.goods_sku_id,
          address_id: this.data.addressInfo.address_id,
          is_self: this.data.expressType[0],
          remark: '',
          use_score: this.data.useCredit ? 1 : 0
        },
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === API_OK) {
        this.pageData.submit = false
        if (res.data.status) {
          wx.showToast({
            title: res.data.status === 1 ? '购买成功' : '购买失败',
            icon: 'success',
            duration: 1500,
            mask: false,
            success: () => {
              setTimeout(() => {
                if (res.data.status === 1) wx.navigateBack({ delta: 1 })
              }, 1500)
            }
          })
        } else {
          this.pay(res.data.payment)
        }
      }
    } catch(err) {
      console.warn(err)
      this.pageData.submit = false
    }
  },
  /**
   * 提交课程订单
   */
  // async submitCourseOrder() {
  //   try {
  //     const res = await buyCourse({
  //       data: {
  //         courses_id: this.data.cart[0].course_id,
  //         score_deduct_type: this.data.useCredit ? 1 : 0
  //       },
  //       callback: wx.hideLoading
  //     })
  //     // console.log(res)
  //     if (res.code === API_OK) {
  //       this.pageData.submit = false
  //       if (res.data.status) {
  //         wx.showToast({
  //           title: res.data.status === 1 ? '兑换成功' : '兑换失败',
  //           icon: 'success',
  //           duration: 1500,
  //           mask: false,
  //           success: () => {
  //             setTimeout(() => {
  //               if (res.data.status === 1) wx.navigateBack({ delta: 1 })
  //             }, 1500)
  //           }
  //         })
  //       } else {
  //         this.pay(res.data.payment)
  //       }
  //     }
  //   } catch(err) {
  //     console.warn(err)
  //     this.pageData.submit = false
  //   }
  // },
  /**
   * 付款
   */
  pay(config) {
    wx.requestPayment({
      timeStamp: config.timeStamp,
      nonceStr: config.nonceStr,
      package: `prepay_id=${config.prepay_id}`,
      signType: 'MD5',
      paySign: config.paySign,
      success: (result)=>{
        // console.log(result)
        if (result.errMsg === 'requestPayment:ok') {
          wx.navigateBack({ delta: 1 })
        }
      },
      fail: (err)=>{
        console.warn(err)
        wx.showToast({ title: '支付失败', icon: 'none', duration: 1500, mask: true })
      },
      complate: () => {
        this.pageData.submit = false
      }
    })
  }
})
